package com.ndood.agent.service.user.impl;

import java.util.Date;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.ndood.agent.core.constaints.AgentConstaints;
import com.ndood.agent.core.constaints.AgentErrCode;
import com.ndood.agent.core.exception.AgentException;
import com.ndood.agent.dao.system.RegionRepository;
import com.ndood.agent.dao.system.UserRepository;
import com.ndood.agent.pojo.system.RegionPo;
import com.ndood.agent.pojo.system.UserPo;
import com.ndood.agent.pojo.system.dto.UserDto;
import com.ndood.agent.service.user.AccountInfoService;
import com.ndood.core.utils.JPAUtil;

@Service
public class AccountInfoServiceImpl implements AccountInfoService{

	@Autowired
	private UserRepository userDao;
	
	@Autowired
	private RegionRepository regionDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Override
	public boolean checkMobile(String mobile) {
		Long count = userDao.countByMobile(mobile);
		return count == 0;
	}
	
	@Override
	public boolean checkEmail(String email) {
		Long count = userDao.countByEmail(email);
		return count == 0;
	}
	
	@Override
	public UserDto getAccountInfoById(String userId) throws Exception {
		if(StringUtils.isBlank(userId)) {
			throw new AgentException(AgentErrCode.ERR_OTHER,"用户不存在！");
		}
		Optional<UserPo> option = userDao.findById(Integer.parseInt(userId));
		if(!option.isPresent()) {
			throw new AgentException(AgentErrCode.ERR_OTHER,"用户不存在！");
		}
		
		UserDto dto = new UserDto();
		UserPo po = option.get();
		JPAUtil.fatherToChild(po, dto);
		
		dto.setProvince(po.getProvince()==null?null:po.getProvince());
		dto.setCity(po.getCity()==null?null:po.getCity());
		dto.setDistrict(po.getDistrict()==null?null:po.getDistrict());
		dto.setDeptId(po.getDepartment()==null?null:po.getDepartment().getId());
		dto.setRoles(po.getRoles());
		// 不能暴露密码
		dto.setPassword(null);
		return dto;
	}

	@Override
	public UserDto getAccountSimpleInfoById(String userId) throws Exception {
		if(StringUtils.isBlank(userId)) {
			throw new AgentException(AgentErrCode.ERR_OTHER,"用户不存在！");
		}
		Optional<UserPo> option = userDao.findById(Integer.parseInt(userId));
		if(!option.isPresent()) {
			throw new AgentException(AgentErrCode.ERR_OTHER,"用户不存在！");
		}
		
		UserPo po = option.get();
		UserDto dto = new UserDto();
		JPAUtil.fatherToChild(po, dto);
		
		// 不能暴露密码
		dto.setPassword(null);
		return dto;
	}

	@Override
	public void updateAccountInfo(UserDto dto) throws Exception {
		dto.setPassword(null);
		dto.setMobile(null);
		dto.setEmail(null);
		dto.setUpdateTime(new Date());
		
		UserPo po = userDao.findById(dto.getId()).get();
		JPAUtil.childToFather(dto, po);
		
		RegionPo province = regionDao.findBySid(dto.getProvinceId());
		po.setProvince(province);
		
		RegionPo city = regionDao.findBySid(dto.getCityId());
		po.setCity(city);
		
		RegionPo district = regionDao.findBySid(dto.getDistrictId());
		po.setDistrict(district);
		
		// Step2: 更新时间
		userDao.save(po);
	}
	
	@Override
	public String registerAccount(UserDto dto) throws Exception {
		// Step1: 补充相关默认字段
		dto.setCreateTime(new Date());
		dto.setUpdateTime(new Date());
		dto.setSex(AgentConstaints.SEX_MAN);
		dto.setStatus(AgentConstaints.STATUS_OK);
		dto.setSort(100);
		dto.setBirthday("2000-01-01");
		if(dto.getPassword()==null) {
			dto.setPassword(passwordEncoder.encode("123456"));
		}else {
			dto.setPassword(passwordEncoder.encode(dto.getPassword()));
		}

		UserPo po = new UserPo();
		RegionPo province = regionDao.findBySid(110000);
		po.setProvince(province);
		
		RegionPo city = regionDao.findBySid(110100);
		po.setCity(city);
		
		RegionPo district = regionDao.findBySid(110101);
		po.setDistrict(district);
		
		JPAUtil.childToFather(dto, po);
		
		// Step2: 保存用户信息
		UserPo userPo = userDao.save(po);
		return String.valueOf(userPo.getId());
	}

	/**
	 * 修改用户邮箱激活状态
	 */
	@Override
	public void activeEmail(String email) throws AgentException {
		UserPo user = userDao.findByEmail(email);
		if(user==null) {
			throw new AgentException(AgentErrCode.ERR_OTHER,"用户不存在！");
		}
		if(user.getEmailStatus()==1) {
			throw new AgentException(AgentErrCode.ERR_OTHER,"邮箱已激活！");
		}
		user.setEmailStatus(1);
		user.setUpdateTime(new Date());
		userDao.save(user);
	}

	/**
	 * 校验密码
	 */
	@Override
	public boolean checkPassword(String userId, String pass) {
		UserPo user = userDao.findById(Integer.parseInt(userId)).get();
		if(!passwordEncoder.matches(user.getPassword(),pass)) {
			return false;
		}
		return true;
	}

	/**
	 * 修改用户密码
	 */
	@Override
	public void changePassword(String userId, String password) {
		UserPo user = userDao.findById(Integer.parseInt(userId)).get();
		user.setPassword(passwordEncoder.encode(password));
		user.setUpdateTime(new Date());
		userDao.save(user);
	}

	@Override
	public UserDto getAccountSimpleInfoByEmail(String email) throws Exception {
		UserPo po = userDao.findByEmailAndEmailStatus(email, 1);
		if(po==null) {
			throw new AgentException(AgentErrCode.ERR_OTHER,"获取用户信息失败，邮箱不存在或者未激活！");
		}
		
		UserDto dto = new UserDto();
		JPAUtil.fatherToChild(po, dto);
		
		// 不能暴露密码
		dto.setPassword(null);
		return dto;
	}

	@Override
	public UserDto getAccountSimpleInfoByMobile(String mobile) throws Exception {
		UserPo po = userDao.findByMobile(mobile);
		if(po==null) {
			throw new AgentException(AgentErrCode.ERR_OTHER,"获取用户信息失败，手机号对应的用户不存在！");
		}
		
		UserDto dto = new UserDto();
		JPAUtil.fatherToChild(po, dto);
		
		// 不能暴露密码
		dto.setPassword(null);
		return dto;
	}
	
}
